﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Chat.API.Models;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Newtonsoft.Json;

namespace Chat.API
{
    /// <summary>
    /// 一对一的聊天集线器处理
    /// </summary>
    [HubName("chat")]
    public class OneToOneHub : Hub
    {
        /// <summary>
        /// 在线用户列表，用于保存连接接入的用户
        /// </summary>
        public static List<User> userList = new List<User>();

        /// <summary>
        /// 当有用户连接的时候
        /// </summary>
        /// <returns></returns>
        public override Task OnConnected()
        {
            //根据当前连接的id判断用户是否已存在于在线用户列表
            var user = userList.FirstOrDefault(t => t.ConnectionId == Context.ConnectionId);
            if (null == user)
            {
                //建立连接时不知道用户名称，仅可以通过上下文【Context.ConnectionId】得知当前的连接id
                userList.Add(new User("", Context.ConnectionId));
            }
            return base.OnConnected();
        }

        /// <summary>
        /// 当前用户断开连接的时候
        /// </summary>
        /// <param name="stopCalled"></param>
        /// <returns></returns>
        public override Task OnDisconnected(bool stopCalled)
        {
            //从在线用户列表中移除断开连接的用户
            var user = userList.FirstOrDefault(t => t.ConnectionId == Context.ConnectionId);
            if (null != user)
            {
                userList.Remove(user);
            }
            UpdateOnlineUser();

            return base.OnDisconnected(stopCalled);
        }

        /// <summary>
        /// 在线用户列表中更新当前用户的姓名
        /// 客户端远程调用
        /// </summary>
        /// <param name="name"></param>
        public void UpdateUserName(string name)
        {
            var currentUser = userList.FirstOrDefault(t => t.ConnectionId == Context.ConnectionId);
            if (null != currentUser)
            {
                currentUser.Name = name;
            }
            UpdateOnlineUser();
        }

        public void UpdateOnlineUser()
        {
            var list = userList.Select(t => new { t.Name, t.ConnectionId }).ToList();

            //Hub 前后端交互是基与json数据格式
            string jsonUser = JsonConvert.SerializeObject(list);
            //通知所有客户端，执行updateOnlineUser方法
            Clients.All.updateOnlineUser(jsonUser);
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="targetConnId"></param>
        /// <param name="message"></param>
        public void SendMessage(string targetConnId, string message)
        {
            var currentUser = userList.FirstOrDefault(t => t.ConnectionId == Context.ConnectionId);
            var targetUser = userList.FirstOrDefault(t => t.ConnectionId == targetConnId);

            if (null != currentUser && null != targetUser)
            {
                //A发消息给B，先确保B收到消息，再告诉A消息已发出
                Clients.Client(targetUser.ConnectionId).addMessage(message, currentUser.Name,
                    currentUser.ConnectionId);

                //A收到的回执
                Clients.Client(currentUser.ConnectionId).addMessage(message, targetUser.Name,
                    targetUser.ConnectionId);
            }
        }
    }
}